<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/auth/auth.php');
include("sockets.php");


function launchError($info) {
				$errarr = array();
				$errarr[] = $info;
				$_SESSION['ERRMSG_ARR'] = $errarr;
				session_write_close();
				header("location: auth/login-form.php");
				exit();
			}

			//Include database connection details
			require_once('db/config.php');

			//Connect to mysql server
			$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
			if($link) {
			
				$db = mysql_select_db(DB_DATABASE);
			
				if($db) {

					$qry="SELECT vmid, vmm_host, vmm_port FROM vm WHERE uid=" . $_SESSION['SESS_USER_ID'] . ";";
					$result=mysql_query($qry);
	
				if($result) {		
					if(mysql_num_rows($result) == 1) {
						$result = mysql_fetch_assoc($result);
						$vmid 	= $result['vmid'];
						$vmmhost = $result['vmm_host'];
						$vmmport = $result['vmm_port'];
					} else {
						launchError("No tienes niguna VM ID asociada, habla con sales@pxcloud.info para contratar una.");
					}
				}
			}}
	
	$clientip = $_SESSION['SESS_USER_IP'];
	$clientport = $_SESSION['SESS_USER_PORT'];
	
	$vmmxml = "<remote_call><function_name>login</function_name><arguments><vmid>$vmid</vmid><ip>$clientip</ip><port>$clientport</port></arguments></remote_call>";

	$response = "Something nasty with sockets..";

	$response = socketsSendXML($vmmhost, $vmmport, $vmmxml);	
	
	if(strpos($response,"<result>0</result>") !== false) {
		header("Location: launch-ok.php");
	} else {
		launchError($response);
	}

?>
